<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
  <link rel="stylesheet" href="/public/bootstrap.min.css">
  <link rel="stylesheet" href="/public/bootstrap-icons-141.css">
  <link rel="stylesheet" href="/public/style-light.css">
  
  <script src="/public/jquery.min.js"></script>
  <script src="/public/dayjs.min.js"></script>
  <script src="/public/bootstrap.bundle.min.js"></script>
  <script src="/public/clipboard.min.js"></script>
  <script src="/public/util.js"></script>
  
  <title>Tag Groups - localtags</title>
</head>
<body>
  <div id="root" class="container" style="max-width: 775px; min-width: 400px;"></div>
  <script>
    
const Alerts = CreateAlerts();

const [InfoBtn, InfoMsg] = CreateInfoPair('使用说明', m('ul').append([
  m('li').text('这里列出最近使用过的标签组，也可以手动添加标签组，主要作用是：方便搜索文件。'),
  m('li').text('当标签组总数量超过上限 (该上限在 config.json 文件中设置) 时，会自动删除最旧的标签组，也可点击垃圾桶图标删除标签组。'),
  m('li').text('点击挂锁图标可保护标签组，受保护的标签组不会被自动删除 (仍可手动删除)。'),
  m('li').text('所谓删除标签组 (不管自动还是手动), 只是不在本页面显示该标签组而已，不会删除标签，也不会解除标签与文件的关联。'),
]));

const Navbar = {
  view: () => m('nav').addClass('navbar navbar-light bg-light').append([
    m('div').addClass('container-fluid').append([
      m('a').attr({title:'main menu',href:'/light/home',type:'button'}).addClass('btn btn-outline-dark').append(
        m('i').addClass('bi bi-house-door'),
      ),
      m('span').addClass('navbar-brand').append([
        'Tag Groups', ' ', m(InfoBtn),
      ]),
      m('a').attr({title:'All Tags',href:'/light/tags',type:'button'})
        .addClass('btn btn-outline-dark').append(
          m('i').addClass('bi bi-tags')
      ),
    ]),
  ]),
};

const GroupList = cc('div');
GroupList.prepend = (group) => {
  const item = createTagGroup(group);
  $(GroupList.id).prepend(m(item));
  item.init();
};

const TagsInput = cc('textarea');
const CheckBtn = cc('button');
const SubmitBtn = cc('button');
const Form = {
  view: () => m('div').append([
    m(TagsInput).addClass('form-control').attr({placeholder:'new tag group'}).focus(() => {
      $(SubmitBtn.id).hide();
      $(CheckBtn.id).show();
    }),
    m('p').addClass('text-end mt-2').append([
        m(CheckBtn).text('check').addClass('btn btn-secondary')
            .attr({type:'button'}).click(Form.check),
        m(SubmitBtn).text('add').addClass('btn btn-primary').attr({type:'button'})
            .hide().click(Form.submit),
    ]),
  ]),

  check: () => {
    const tags = tagsStringToSet($(TagsInput.id).val());
    if (tags.size == 0) {
      $(TagsInput.id).focus();
      return;
    }
    /*
    if (tags.size == 1) {
      Alerts.insert('info', '标签组至少需要 2 个标签');
      $(TagsInput.id).focus();
      return;
    }
    */
    Alerts.clear();
    $(TagsInput.id).val(addPrefix(tags, '#'));
    $(CheckBtn.id).hide();
    $(SubmitBtn.id).show();
    TagsInput.currentTagsSet = tags;
  },

  submit: () => {
    const body = new FormData();
    body.append('tags', JSON.stringify(Array.from(TagsInput.currentTagsSet)));
    ajax({method:'POST',url:'/api/add-taggroup',body:body,alerts:Alerts,buttonID:SubmitBtn.id},
        (group) => {
          GroupList.prepend(group);
          Alerts.insert('success', '添加了新标签组: ' + addPrefix(group.Tags, '#'));
        });
  },
};

$('#root').append([
  m(Navbar).addClass('mt-2 mb-5'),
  m(InfoMsg).hide(),
  m(Form),
  m(Loading),
  m(Alerts).addClass('my-3'),
  m(GroupList),
  m(BottomLine),
]);

init()

function init() {
  ajax({method:'GET',url:'/api/tag-groups',alerts:Alerts},
      (groups) => {
        if (!groups) {
          Alerts.insert('info', '没有标签组，一个都没有');
        }
        groups.forEach(GroupList.prepend);
      }, null,
      () => {
        // onAlways
        Loading.hide();
        window.setTimeout(() => { $(TagsInput.id).focus(); }, 100);
      });
}

function createTagGroup(group) {
  const tagGroupStr = addPrefix(group.Tags);
  const utime = dayjs.unix(group.UTime).format('MMMM D, YYYY');
  const self = cc('div', 'g'+group.ID);

  self.Alerts = CreateAlerts();

  self.view = () => m('div').attr({id: self.raw_id}).addClass('TagGroup card my-3').append([
    m('div').addClass('card-body').append([
      m('div').append([
        m('span').text(utime).addClass('Date small text-muted'),
        ' ',
        m('span').text('PROTECTED').addClass('Protected').hide(),
        m('span').text('DELETED').addClass('Deleted').hide(),
        ' ',
        m('i').attr({title:'copy'}).addClass('IconBtn bi bi-stickies'),
        m('i').attr({title:'protect'}).addClass('IconBtn bi bi-lock').click(self.protect),
        m('i').attr({title:'unprotect'}).addClass('IconBtn bi bi-unlock').hide().click(self.unprotect),
        m('i').attr({title:'delete'}).addClass('IconBtn bi bi-trash').click(self.delete),
      ]),
      m('div').addClass('Tags'),
      m('div').addClass('TagsText small text-muted').text('tags: ' + addPrefix(group.Tags, '#')).hide(),
    ]),
    m(self.Alerts),
  ]);

  self.delete = () => {
    const url = '/api/delete-taggroup/'+group.ID;
    const buttonID = self.id + ' .bi-trash';
    ajax({method:'GET',url:url,alerts:self.Alerts,buttonID:buttonID},
        () => {
          $(self.id+' .Protected').hide();
          $(self.id+' .Deleted').show();
          $(self.id+' .bi').hide();
          $(self.id+' .Tags').hide();
          $(self.id+' .TagsText').show();
        });
  };

  const clipboard = new ClipboardJS(self.id+' .bi-stickies', {
    text: () => { return tagGroupStr; }
  });
  clipboard.on('success', () => {
    self.Alerts.insert('success', '已复制标签组');
  });
  clipboard.on('error', e => {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
    self.Alerts.insert('danger', '复制失败，详细信息见控制台');
  });

  self.toggleProtect = () => {
    $(self.id + ' .Protected').toggle(); 
    $(self.id + ' .bi-lock').toggle();
    $(self.id + ' .bi-unlock').toggle();
  };

  self.protect = () => {
    const url = '/api/protect-taggroup/'+group.ID;
    const buttonID = self.id + ' .bi-lock';
    self.setProtected(url, buttonID)
  };

  self.unprotect = () => {
    const url = '/api/unprotect-taggroup/'+group.ID;
    const buttonID = self.id + ' .bi-unlock';
    self.setProtected(url, buttonID)
  };

  self.setProtected = (url, buttonID) => {
    ajax({method:'GET',url:url,alerts:self.Alerts,buttonID:buttonID},
        () => {
          self.toggleProtect();
        });
  }

  self.init = () => {
    const tagsElem = $(self.id + ' .Tags');
    group.Tags.forEach(tag => {
      const item = m('a').text(tag).addClass('badge bg-light text-dark text-decoration-none')
        .attr({href: '/light/tag?name=' + encodeURIComponent(tag)});
      tagsElem.append(item);
    });

    const groupLink = '/light/search?tags=' + encodeURIComponent(tagGroupStr);
    const groupItem = m('a').text('search').attr({title:'search tag group', href:groupLink})
      .addClass('badge bg-secondary text-white text-decoration-none');
    tagsElem.append(groupItem);

    if (group.Protected) {
      self.toggleProtect();
    }
  };

  return self;
}

  </script>
</body>
</html>